/**
 * 
 */
package container;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import servlet.AbstractServletListener;

import logging.Level;
import logging.Logger;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * @author think
 * 模板操作类
 */
public class TemplateHelper {
	
	private static final Logger LOGGER = Logger.getLogger(AnnotionHelper.class
			.getName());
	
	static Configuration freeMakercfg = null;
	static TemplateHelper templateHelper = null;
	
	public static TemplateHelper getInstance(){
		if(templateHelper==null){
			templateHelper = new TemplateHelper();
			freeMakercfg = new Configuration();
			try {
				String templatePath = AbstractServletListener.getWebRoot()+"templates";
				LOGGER.info("templatePath:"+templatePath);
				freeMakercfg.setDirectoryForTemplateLoading(new File(templatePath));
			} catch (IOException e) {
				LOGGER.log(Level.WARN,"TemplateHelper init fail",e);
			}
		}
		return templateHelper;
	}
	
	
	public void render(String templateName,Map dataModel,Writer writer) throws IOException, TemplateException{
		Template bookTemplate = freeMakercfg.getTemplate(templateName);//模板对象
		bookTemplate.process(dataModel, writer);
		writer.flush();
	}
}
